package dag

import (
	"hxy/repo/cmd"
	"hxy/repo/database"
	"log"

	"github.com/google/uuid"
)

type PipelineTask = cmd.PipelineTask
type CITaskStatus = cmd.CITaskStatus

var CICompiling = cmd.CICompiling
var CIUnknow = cmd.CIUnknow
var CIError = cmd.CIError
var CIFinished = cmd.CIFinished

// JavaTask , extend from the PipelineTask , add the java ci status value : CITaskStatus
type JavaTask struct {
	Task  PipelineTask
	State CITaskStatus
}

// Conver the JavaTask's state const to the string
func (jt JavaTask) StateStr() string {
	switch jt.State {
	case CICompiling:
		return "CICompiling"
	case CIUnknow:
		return "CIUnknow"
	case CIError:
		return "CIError"
	case CIFinished:
		return "CIFinished"
	default:
		return "CIUnknow"
	}
}

// # Generate a Java Compile task from the
// parame : @project_path and the @gitid
func BuildJavaTask(proj_path string, gitid int, hashValue string) JavaTask {
	var task = PipelineTask{
		Git_id:  gitid,
		ID:      uuid.New(),
		RunProg: "mvn",
		Command: "clean package -Dmaven.test.skip=true",
		Dir:     proj_path,
		State:   "CIUnknow",
		GitHash: hashValue,
	}
	return JavaTask{
		State: CIUnknow,
		Task:  task,
	}
}

func (jt JavaTask) ID() string {
	return "JavaTask-" + jt.Task.GitHash
}
func (jt JavaTask) Run() error {
	database.CreatePipelineTask(jt.Task)
	jt.routeTaskState(CICompiling)
	err := jt.Task.Run()
	if err != nil {
		jt.routeTaskState(CIError)
		log.Printf("Error in java ci(%s)_ :%s",
			jt.Task.ID.String(),
			err.Error())

		database.AddTaskEndtiem(jt.Task)
		return err
	} else {
		jt.routeTaskState(CIFinished)
		database.AddTaskEndtiem(jt.Task)
		return nil
	}

}

// Route the State of the Ci task
func (jt JavaTask) routeTaskState(state CITaskStatus) {
	jt.State = state
	database.ChangePipelineState(jt.Task, jt.StateStr())
}
